<?php
class Chat extends CI_Controller {
	public function __construct() {
		parent::__construct();
		$this->load->model('chat_model');
		$this->authorize_model->loginAuthorize();
	}

	public function index() {
		return $this->view();
	}

	public function view() {
		$data['username'] = $this->session->userdata('username');
		$data['name'] = $this->session->userdata('name');
		$this->load->view('templates/header', $data);
		$this->load->view('chat/chat');
		$this->load->view('templates/footer');
	}

	public function calc() {
		$toId = $this->session->userdata('username');

		$start_time = time();
		$query = $this->chat_model->queryMsg($toId);
		while (!$query) {
			if (time() - $start_time > 60) {
				echo json_encode(array());
				return;
			}
			sleep(2);
			$query = $this->chat_model->queryMsg($toId);
		}

		echo json_encode($query);
	}

	public function rec() {
		$msgData['fromName'] = $this->session->userdata('name');
		$msgData['fromId'] = $this->session->userdata('username');
		$msgData['text'] = $this->input->post('text');
		$msgData['toId'] = $this->input->post('toId');
		$msgData['time'] = date('Y-m-d H:i:s', time());

		$type = $this->input->post('type');

		$res = FALSE;

		if ($type == 'group') {
			$res = $this->chat_model->sendToGroup($msgData);
		} elseif ($type == 'user') {
			$res = $this->chat_model->sendToUser($msgData)
			&& $this->chat_model->sendToSelf($msgData);
		}

		echo json_encode(array(
			'status' => $res,
			'time' => $msgData['time'],
			'text' => $msgData['text'],
		));
	}

	public function conf() {
		$json = $this->input->post('json');
		if (!$json) {
			echo 'failed!';
			return;
		}
		$msgs = json_decode($json, true);
		if (!$this->chat_model->confirmMsg($msgs)) {
			echo 'failed!';
			return;
		}
		echo 'confirmed!';

	}

}